""" 
wifi连接
"""

from machine import Pin
import time
import network
import usocket

led1 = Pin(15, Pin.OUT)
ssid = "esp32_test_wifi"
password = "12356789"

ip = "192.168.137.1"
port = 8899

def wifi_connec():
    wlan = network.WLAN(network.STA_IF)  # STA模式
    wlan.active(True)   # 激活,连接wifi
    start_time = time.time()

    if not wlan.isconnected():
        print("connecting to network...")
        wlan.connect(ssid, password)
        while not wlan.isconnected():
            if time.time() - start_time > 15:
                print("connect timeout")
                return False

            led1.value(1)
            time.sleep(300)
            led1.value(0)
            time.sleep(300)
    else:
        print("wifi connected:")
    led1.value(1)
    print("network config:", wlan.ifconfig())
    return True


def tcp_connect():
    sock = usocket.socket()
    sock.connect((ip,port))
    sock.send("hello esp32 client")
    
    while True:
        data = sock.recv(1024)
        if data:
            print(data)
            sock.send("esp32 send:"+data.decode("utf-8"))
        else:
            print("no data, timeout")
        time.sleep(200)


if __name__ == "__main__":
    if wifi_connec():
        tcp_connect()
